import React, { useEffect, useCallback, Fragment } from 'react';
import Typography from '@material-ui/core/Typography';
import { Box, Grid, Container } from '@material-ui/core';
import { usePage } from '../hooks/page';

import ProjectItem from '../component/ProjectItem';
import HeaderCard from '../component/HeaderCard';

import BlogItem from '@/component/BlogItem';
import { useModel, useHistory } from 'umi';
import { IBlog, IProject } from '@/interface';
import { useStore } from 'reto';
import Blog from '@/store/blog';
import User from '@/store/user';
import Project from '@/store/project';
import StoreyTitle from '@/component/StoreyTitle';
import { stripHTML } from '@/utils/html';
import Footer from '@/component/Footer';

export default () => {
  usePage({
    appBarTitleText: '首页',
    appBarStyle: 'none',
  });
  const blogModel = useStore(Blog);
  const blogListModel = blogModel.listModel;
  const blogList = (blogListModel.data || {}).list;
  const projectModel = useStore(Project);
  const projectListModel = projectModel.listModel;
  const projectList = (projectListModel.data || {}).list;

  const history = useHistory();

  const handleBlogItemClick = useCallback((item?: IBlog) => {
    item && history.push('/blog/' + item.id);
  }, []);

  return (
    <Container
      style={{
        paddingTop: 20,
      }}
    >
      <HeaderCard />

      <StoreyTitle>我开发的</StoreyTitle>

      <Box display="flex" flexDirection="row" flexWrap="wrap">
        {projectList &&
          projectList.map((item, index) => (
            <Fragment key={item.id}>
              <ProjectItem
                id={item.id}
                icon={item.icon}
                title={item.name}
                intro={item.summary}
              />
              {index !== projectList.length - 1 ? <Box width={16} /> : null}
            </Fragment>
          ))}
      </Box>

      <StoreyTitle>我瞎写的</StoreyTitle>

      <Grid container spacing={3}>
        {blogList &&
          blogList.map(item => (
            <Grid item xs={12} sm={6} md={4} key={item.id}>
              <BlogItem
                title={item.title}
                content={stripHTML(item.content)}
                cover={item.pic}
                onClick={() => handleBlogItemClick(item)}
              />
            </Grid>
          ))}
        {blogListModel.loadData.loading &&
          Array.from(new Array(2)).map((item, index) => (
            <Grid item xs={12} sm={6} md={4} key={-index}>
              <BlogItem />
            </Grid>
          ))}
      </Grid>

      <Footer />
    </Container>
  );
};
